const fs = require("fs");
const path = require("path");

// 正则匹配字符串
const regStyle = /<style>[\s\S]*<\/style>/;
const regScript = /<script>[\s\S]*<\/script>/;

// 读文件
fs.readFile(path.join(__dirname, "/index.html"), "utf-8", (err, datastr) => {
  if (err) {
    return console.log("Failed to read file" + err.message);
  }
  resolveCss(datastr);
  resolveJs(datastr);
  resolveHtml(datastr);
});
function resolveCss(CssStr) {
  const oldStr = regStyle.exec(CssStr);
  const newCss = oldStr[0].replace("<style>", " ").replace("</style>", " ");
  fs.writeFile(
    path.join(__dirname, "./4-path&file-test/index.css"),
    newCss,
    (err) => {
      if (err) {
        return console.log("Failed to write file" + err.message);
      }
      console.log("Success to write file");
    }
  );
}
function resolveJs(JsStr) {
  const oldStr = regScript.exec(JsStr);
  const newJS = oldStr[0].replace("<script>", " ").replace("</script>", " ");
  fs.writeFile(
    path.join(__dirname, "./4-path&file-test/index.js"),
    newJS,
    (err) => {
      if (err) {
        return console.log("Failed to write file" + err.message);
      }
      console.log("Success to write file");
    }
  );
}
function resolveHtml(htmlStr) {
  const newHtml = htmlStr
    .replace(regStyle, "<link rel='stylesheet' href='./index.css'>")
    .replace(regScript, "<script src='./index.js'></script>");
  fs.writeFile(
    path.join(__dirname, "./4-path&file-test/index.html"),
    newHtml,
    (err) => {
      if (err) return console.log("Failed is write file" + err.message);
      console.log("Success to write file");
    }
  );
}
